'use strict';
var testcaseRelationship = require('../models/testcaseRelationship');
var testcaseRelationshipModel = testcaseRelationship.testCaseRelationship;

function getOrderedDependencies(dependencies,orderedDependencies) {
    if (dependencies.length > 0){
        dependencies.forEach(function (dep) {
            getOrderedDependencies(dep.dependency,orderedDependencies);
            orderedDependencies.push({'testCaseId' : dep.testCaseId});
        })
    }
    return orderedDependencies;
};

function getDependencyTestcase(req,res,next) {
    let testCaseId = req.params.testCaseId;
    testcaseRelationshipModel.findOne({'testCaseId': testCaseId}, function (err, data) {
        if (err) {
            next(err);
        } else {
            if (data){
                let orderedDependencies = [];
                orderedDependencies = getOrderedDependencies(data.dependency,orderedDependencies);
                res.send(orderedDependencies);
            }else{
                res.send(null);
            }
        }
    });
};

function getRelationshipByTestcaseId(testCaseId) {
   return new Promise((resolve,reject)=>{
       testcaseRelationshipModel.findOne({'testCaseId':testCaseId},function (err, relationship) {
           if (err) {
               reject(err);
           } else {
               resolve(relationship);
           }
       });
   });
}

function addRelationship(data, testCaseId) {
    return new Promise((resolve, reject) => {
        var relationshipSave = new testcaseRelationshipModel({
            testCaseId: testCaseId,
            dependency: data.relationship.dependency
        });
        relationshipSave.save(function(err, docs) {
            if (err) {
                reject(err);
            } else {
                resolve(docs)
            }
        })
    })
}

function updateRelationship(data, condition) {
    return new Promise((resolve, reject) => {
        var relation = data.relationship;
        testcaseRelationshipModel.update(condition, relation, function(err, docs) {
            if (err) {
                reject(err);
            } else {
                resolve(docs)
            }
        })
    });
}

module.exports = {
    getOrderedDependencies : getOrderedDependencies,
    getDependencyTestcase : getDependencyTestcase,
    getRelationshipByTestcaseId : getRelationshipByTestcaseId,
    addRelationship : addRelationship,
    updateRelationship: updateRelationship
}